package cn.tedu.jxc.repo.impl;

import cn.tedu.jxc.pojo.vo.UserStandardVO;
import cn.tedu.jxc.repo.UserRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class UserRedisRepositoryImpl implements UserRedisRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void saveList(List<UserStandardVO> userStandardVOList) {
        String key = USER_LIST_KEY;
        for (UserStandardVO userStandardVO : userStandardVOList) {
            redisTemplate.opsForList().rightPush(key,userStandardVO);
        }
        redisTemplate.opsForSet().add(USER_KEYS_KEY, key);

    }

    @Override
    public List<UserStandardVO> getList() {
        return getListRange(0L,-1L);
    }

    @Override
    public List<UserStandardVO> getListRange(Long start, Long end) {
        String key = USER_LIST_KEY;
        List<Serializable> lists = redisTemplate.opsForList().range(key, start, end);
        List<UserStandardVO> userStandardVOS = new ArrayList<>();
        for (Serializable range : lists) {
            userStandardVOS.add((UserStandardVO) range);
        }
        return userStandardVOS;
    }

    @Override
    public void deleteAll() {
        String key = USER_KEYS_KEY;
        Set<Serializable> members = redisTemplate.opsForSet().members(key);
        Collection<String> collection = new ArrayList<>();
        for (Serializable member : members) {
            collection.add((String) member);
        }
        collection.add(key);
        redisTemplate.delete(collection);
    }
}
